
const https = require('https');

const path = require('path')
const multer = require('multer')
const storage = multer.diskStorage({
    destination: './uploads',
    filename: function (req, file, cb) {
        ///获取图片类型
        // console.log(file)
        let fileType = file.originalname.split('.')
        fileType = fileType[fileType.length - 1]
        cb(null, snowflake() + '.' + fileType)
    }
})
const upload = multer({ storage: storage})

///雪花算法生成id
const snowflake = require('./snowflake')
const SQLHelper = require('./SQLHelper')
const {formatTime} = require('./util')
module.exports = function(app){
///登录拦截中间件
function loginRouter(req,res,next){
    if(req.method.toUpperCase() == 'OPTIONS'){
        next()
        return;
    }
    let token = req.headers.token
    if(token){
        SQLHelper(`select * from session where id = ${token} and state = 1`).then(ret => {
            if(ret.length){
                let session = ret[0]
                //2h
                if(new Date().getTime() - session.createTime < 2 * 60 * 60 * 1000){
                    req.session = {
                    userId:session.userId,
                    userName:session.userName
                    }
                    next()
                }else
                    res.status(400).send({errorMsg:'登录超时'})
            }else{
                res.status(400).send({errorMsg:'当前用户未登录'})
            }
        })
    }else{
        res.status(405).send({errorMsg:'缺少token,请先进行登录'})
    }
  }

  
  ///让初登陆以为的所有小程序接口都先验证登陆
  app.use('/admin',loginRouter)

  app.post('/upload',upload.single('file'),(req, res) => {
    // console.log(req.file);
    res.send(req.file)
})
  
//   //解析body中间件
//   app.use(bodyParser.json({limit:'100mb'}))
  
  
  // 管理后台登陆
  app.post('/login', (req, res) => {
    let userName = req.body.userName
    let passWord = req.body.passWord
    if(userName && passWord){
        SQLHelper(`
            select * from user where userName = '${userName}'
        `).then(users => {
            if(users.length){//正常登陆
                let user = users[0]
                if(passWord == user.passWord){
                    let token = snowflake()
                    ///缓存token到session表
                    SQLHelper(`
                    INSERT INTO session(id,userId,userName,inTime,createTime,platform) 
                    VALUES(${token},'${user._id}','${user.nickName}','${formatTime(new Date())}','${new Date().getTime()}','admin')
                    `).then(ret => {
                      res.send({
                          nickName:user.nickName,
                          token,
                          photo:user.photo,
                          _id:user._id
                      })
                    })
                }else{
                    res.send({errorMsg:'密码错误'})
                }
            }else{
                res.send({errorMsg:'当前用户不存在'})
            }
        })
    }else{
        res.send({errorMsg:'用户名和密码不能为空'})
    }
  })
  // 退出登陆
  app.get('/admin/logout',(req,res) => {
    SQLHelper(`
        update session set outTime = '${formatTime(new Date())}' , state = 0
        where id = '${req.headers.token}'
    `).then(ret => {
        res.send({msg:'退出登陆成功'})
    })
  })

  //修改密码
  app.post('/admin/changePassWord',(req,res) =>{
      let userId = req.session.userId
      let passWord = req.body.passWord
      let newPassWord = req.body.newPassWord
      if(passWord && newPassWord){
          //查询用户
        SQLHelper(`select passWord from user where _id = ${userId}`).then(users => {
            let user = users[0]
            //比对原密码
            if(user.passWord == passWord){
                //修改密码
                SQLHelper(`update user set passWord = '${newPassWord}' where _id = ${userId}`).then(ret => {
                    res.send({msg:'修改密码成功'})
                })
            }else{
                res.send({errorMsg:'原密码错误'})
            }
          })
      }else{
          res.send({errorMsg:'原密码和新密码不能为空'})
      }
  })

  //获取首页轮播图列表
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  ///type 类型 非必填 banner,轮播图 category,分类 recommend,为你推荐 不填搜索全部
  app.get('/admin/index',(req,res) => {
      let pageSize = req.query.pageSize || 10
      let pageNum = req.query.pageNum || 1
      let offset = (pageNum - 1) * pageSize
      let title = req.query.title
      let type = req.query.type 
      let whereSql = 'from index_region where state = 1'
      //按类型查询
      if(type) whereSql += ` and type = '${type}'`
      //按标题关键字搜索
      if(title) whereSql += ` and title like "%${title}%"`
      SQLHelper(`select count(*) as total ${whereSql};
                 select * ${whereSql}
                 limit ${pageSize} offset ${offset}`).then(ret => {
        res.send({
            totale:ret[0][0].total,
            rows:ret[1]
        })
    })
  })
  ///新增首页项目
  ///img 图片地址 必填
  ///url 链接地址 非必填
  ///title 标题 轮播图不填, 其它必填
  ///status 是否启用 非必填 1,启用 0,停用
  ///type 类型 非必填 banner(默认),轮播图 category,分类 recommend,为你推荐
  app.post('/admin/index',(req,res) =>{
      let img = req.body.img,url = req.body.url,status = req.body.status
      let type = req.body.type || 'banner',title = req.body.title 
      if(type != 'banner' && !title){
          res.send({errorMsg:'标题不能为空'})
          return
      }
      if(status != 1) status = 0 //默认启用
      if(img){
        let createTime = new Date().getTime()
        SQLHelper(`
        INSERT INTO index_region(title,img,url,status,state,createTime,unitId,type)
        VALUES('${title}','${img}','${url}','${status}',1,${createTime},'juzao','${type}')
        `).then(ret =>{
            res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
        })
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
  })
  ///修改首页项目
  ///indexId 主码_id 必填
  app.put('/admin/index',(req,res) =>{
    if(req.body.indexId){
        let updateTime = new Date().getTime()
        let updateKey = ['img','url','title','status']
        let updateValues = [`updateTime=${updateTime}`]
        for(let i = 0; i < updateKey.length; i ++){
            let key = updateKey[i],value = req.body[key]
            if(value !== undefined) updateValues.push(`${key}='${value}'`)
        }
        SQLHelper(`UPDATE index_region set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret =>{
            res.send(ret)
        })
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
  })


//删除地址  逻辑删除
app.delete('/admin/index',(req,res) =>{
    let indexId = req.query.indexId
    if(indexId){
        SQLHelper(`
        UPDATE index_region
        set state = 0
        WHERE _id = ${indexId}
        `).then(ret =>{
            res.send(ret)
      })
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})

 //获取新闻管理列表
app.get('/admin/index/news',(req,res) =>{
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let title = req.query.title
    let type = req.query.type
    let whereSql = 'from article where state = 1'
    //按类型搜索
    if(type) whereSql += ` and type = '${type}'`
    //按标题关键字搜索
    if(title) whereSql += ` and title like "%${title}%"`
    SQLHelper(`select count(*) as total ${whereSql};
               select * ${whereSql}
               limit ${pageSize} offset ${offset}`).then(ret => {
        res.send({
          total:ret[0][0].total,
          rows:ret[1]
        })
        
    })
  })
  //新增新闻
app.post('/admin/index/news',(req,res) =>{
    let img = req.body.img,
    status = req.body.status,
    type = req.body.type,
    title = req.body.title,
    digest = req.body.digest,
    hot = req.body.hot,
    userId = req.body.userId
    if(type != 'news' && !title){
      res.send({errorMsg:'标题不能为空'})
      return
    }
    if(status != 1) status = 0
    if(hot != 1) hot = 0
    if(title){
      let createTime = new Date().getTime()
       SQLHelper(`
        INSERT INTO article (title,img,digest,status,state,createTime,unitId,type,userId) VALUES 
        ('${title}','${img}','${digest}','${status}',1,'${createTime}','juzao','news','${userId}')
       `).then(ret => {
          res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
      })
    }else{
      res.send({errorMsg:'请传入参数错误'})
    }
  })

  //修改新闻
app.put('/admin/index/news',(req,res) =>{
    if(req.body.indexId){
      //需要修改的项
      let updateTime = new Date().getTime()
      let updateKey = ['img','title','digest','userId',]
      let updataValues = [`updateTime=${updateTime}`]
  
      for(let i = 0;i < updateKey.length; i ++){
        let key = updateKey[i],value = req.body[key]
        if(value !== undefined)  updataValues.push(`${key}='${value}'`) 
        
      }
       SQLHelper(`UPDATE article set ${updataValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    }else{
      res.send({errorMsg:'请传入参数错误'})
    }
  })
//删除新闻
app.delete('/admin/index/news',(req,res) => {
    let indexId = req.query.indexId
    if(indexId){
        SQLHelper(`
        UPDATE article 
        set state = 0 
        WHERE _id = ${indexId}
        `).then(ret => {
            res.send(ret)
          })
    }else{
  
    }
    
  })
    
  // //获取品牌管理列表
app.get('/admin/index/brand',(req,res) =>{
  let pageSize = req.query.pageSize || 10
  let pageNum = req.query.pageNum || 1
  let offset = (pageNum - 1) * pageSize
  let name = req.query.name
  let whereSql = 'from brand where state = 1'
  let type = req.query.type
  //按类型搜索
  if(type) whereSql += ` and type = '${type}'`  //按标题关键字搜索
   //按品牌关键字搜索
  if(name) whereSql += ` and name like "%${name}%"`
  SQLHelper(`select count(*) as total ${whereSql};
             select * ${whereSql}
             limit ${pageSize} offset ${offset}`).then(ret => {
      res.send({
        total:ret[0][0].total,
        rows:ret[1]
      })
      
  })
})

//新增品牌
app.post('/admin/index/brand',(req,res) =>{
  let name = req.body.name,
  img = req.body.img,
  type = req.body.type,
  sort = req.body.sort,
  banner = req.body.banner
  
  if(type != 'brand' && !name){
    res.send({errorMsg:'标题不能为空'})
    return
  }
  if(name){
    let createTime = new Date().getTime()
     SQLHelper(`
      INSERT INTO brand (name,img,type,sort,banner,unitId,createTime) VALUES 
      ('${name}','${img}','${type}','${sort}','${banner}','juzao','${createTime}')
     `).then(ret => {
        res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
    })
  }else{
    res.send({errorMsg:'请传入参数错误'})
  }
})

//删除品牌
app.delete('/admin/index/brand',(req,res) => {
  let indexId = req.query.indexId
  if(indexId){
      SQLHelper(`
      UPDATE brand 
      set state = 0 
      WHERE _id = ${indexId}
      `).then(ret => {
          res.send(ret)
        })
  }else{
    res.send({errorMsg:'请传入参数错误'})
  }
  
})

//修改品牌信息
//indexId 主码_id 必填
app.put('/admin/index/brand',(req,res) =>{
  if(req.body.indexId){
    //需要修改的项
    let updateTime = new Date().getTime()
    let updateKey = ['name','img','sort','banner']
    let updataValues = [`updateTime=${updateTime}`]

    for(let i = 0;i < updateKey.length; i ++){
      let key = updateKey[i],value = req.body[key]
      if(value !== undefined)  updataValues.push(`${key}='${value}'`) 
      
    }
     SQLHelper(`UPDATE brand set ${updataValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
      res.send(ret)
    })
  }else{
    res.send({errorMsg:'请传入参数错误'})
  }
})

// //获取商品管理列表
app.get('/admin/index/goods',(req,res) =>{
  let pageSize = req.query.pageSize || 10
  let pageNum = req.query.pageNum || 1
  let offset = (pageNum - 1) * pageSize
  let name = req.query.name
  let whereSql = 'from product where state = 1'
  let type = req.query.type
  let brandId = req.query.brandId
  //按类型搜索
  if(type) whereSql += ` and type = '${type}'`  //按标题关键字搜索
  if(brandId) whereSql += ` and brandId = '${brandId}'`  //按品牌关键字搜索
  if(name) whereSql += ` and name like "%${name}%"`
  SQLHelper(`select count(*) as total ${whereSql};
             select * ${whereSql}
             limit ${pageSize} offset ${offset}`).then(ret => {
      res.send({
        total:ret[0][0].total,
        rows:ret[1]
      })
      
  })
})

//新增商品
app.post('/admin/index/goods',(req,res) =>{
  let name = req.body.name,
  brandId = req.body.brandId,
  img = req.body.img,
  description = req.body.description,
  specification = req.body.specification,
  content = req.body.content,
  sales = req.body.sales,
  status = req.body.status,
  functionality = req.body.functionality,
  type = req.body.type
  if(type != 'goods' && !name){
    res.send({errorMsg:'标题不能为空'})
    return
  }
  if(status != 1) status = 0
  if(functionality != 1) functionality = 0 
  if(name){
    let createTime = new Date().getTime()
     SQLHelper(`
      INSERT INTO product (name,brandId,img,description,state,createTime,specification,content,sales,status,functionality,type) VALUES 
      ('${name}','${brandId}','${img}','${description}',1,'${createTime}','${specification}','${content}','${sales}',1,'${functionality}','goods')
     `).then(ret => {
        res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
    })
  }else{
    res.send({errorMsg:'请传入参数错误'})
  }
})

//删除
app.delete('/admin/index/goods',(req,res) => {
  let indexId = req.query.indexId
  if(indexId){
      SQLHelper(`
      UPDATE product 
      set state = 0 
      WHERE _id = ${indexId}
      `).then(ret => {
          res.send(ret)
        })
  }else{
    res.send({errorMsg:'请传入参数错误'})
  }
})

//修改商品信息
//indexId 主码_id 必填
app.put('/admin/index/goods',(req,res) =>{
  if(req.body.indexId){
    //需要修改的项
    let updateTime = new Date().getTime()
    let updateKey = ['name','brandId','img','description','specification','content','sales','status','functionality']
    let updataValues = [`updateTime=${updateTime}`]

    for(let i = 0;i < updateKey.length; i ++){
      let key = updateKey[i],value = req.body[key]
      if(value !== undefined)  updataValues.push(`${key}='${value}'`) 
      
    }
     SQLHelper(`UPDATE product set ${updataValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
      res.send(ret)
    })
  }else{
    res.send({errorMsg:'请传入参数错误'})
  }
})

// //获取分类管理列表
app.get('/admin/index/category',(req,res) =>{
  let pageSize = req.query.pageSize || 10
  let pageNum = req.query.pageNum || 1
  let offset = (pageNum - 1) * pageSize
  let name = req.query.name
  let whereSql = 'from category where state = 1'
  let type = req.query.type
  let parentId = req.query.parentId
  let img = req.query.img
  //按类型搜索
  if(type) whereSql += ` and type = '${type}'`  //按标题关键字搜索
  if(parentId) whereSql += ` and parentId = '${parentId}'`  //按品牌关键字搜索
  if(name) whereSql += ` and name like "%${name}%"`
  if(img) whereSql += ` and name like "%${img}%"`
  SQLHelper(`select count(*) as total ${whereSql};
             select * ${whereSql}
             limit ${pageSize} offset ${offset}`).then(ret => {
      res.send({
        total:ret[0][0].total,
        rows:ret[1]
      })
      
  })
})

//新增分类信息
app.post('/admin/index/category',(req,res) =>{
  let name = req.body.name,
  id = req.body.id,
  parentId = req.body.parentId,
  img = req.body.img,
  level = req.body.level,
  sort = req.body.sort,
  state = req.body.state,
  type = req.body.type
  if(type != 'category' && !name){
    res.send({errorMsg:'标题不能为空'})
    return
  }
  if(state != 1) state= 0
  if(name){
    let createTime = new Date().getTime()
     SQLHelper(`
      INSERT INTO category (name,id,img,parentId,state,createTime,level,sort,type) VALUES 
      ('${name}','${id}','${img}','${parentId}',1,'${createTime}','${level}','${sort}','category')
     `).then(ret => {
        res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
    })
  }else{
    res.send({errorMsg:'请传入参数错误'})
  }
})

//删除分类信息
app.delete('/admin/index/category',(req,res) => {
  let indexId = req.query.indexId
  if(indexId){
      SQLHelper(`
      UPDATE category 
      set state = 0 
      WHERE _id = ${indexId}
      `).then(ret => {
          res.send(ret)
        })
  }else{
    res.send({errorMsg:'请传入参数错误'})
  }
})

//修改分类信息
//indexId 主码_id 必填
app.put('/admin/index/category',(req,res) =>{
  if(req.body.indexId){
    //需要修改的项
    let updateTime = new Date().getTime()
    let updateKey = ['name','id','img','parentId','level','sort','state']
    let updataValues = [`updateTime=${updateTime}`]

    for(let i = 0;i < updateKey.length; i ++){
      let key = updateKey[i],value = req.body[key]
      if(value !== undefined)  updataValues.push(`${key}='${value}'`) 
      
    }
     SQLHelper(`UPDATE category set ${updataValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
      res.send(ret)
    })
  }else{
    res.send({errorMsg:'请传入参数错误'})
  }
})

// //获取单品管理列表
app.get('/admin/index/personproduct',(req,res) =>{
  let pageSize = req.query.pageSize || 10
  let pageNum = req.query.pageNum || 1
  let offset = (pageNum - 1) * pageSize
  let skuId= req.query.skuId
  // let salePrice = req.query.salePrice
  // let originalPrice= req.query.originalPrice
  // let productId= req.query.productId
  let productName = req.query.productName
  // let img = req.query.img 
  // let props= req.query.props
  // let skuSpecification = req.query.skuSpecification
  let whereSql = 'from sku where state = 1'
  let type = req.query.type
  //按类型搜索
  if(skuId) whereSql += ` and skuId = '${skuId}'`  //按标题关键字搜索
  if(type) whereSql += ` and type = '${type}'`  //按品牌关键字搜索
  if(productName) whereSql += ` and productName like "%${productName}%"`
  SQLHelper(`select count(*) as total ${whereSql};
             select * ${whereSql}
             limit ${pageSize} offset ${offset}`).then(ret => {
      res.send({
        total:ret[0][0].total,
        rows:ret[1]
      })
      
  })
})

//新增单品项目
app.post('/admin/index/personproduct',(req,res) =>{
  let skuId = req.body.skuId,
  salePrice = req.body.salePrice,
  originalPrice = req.body.originalPrice,
  productId = req.body.productId,
  productName = req.body.productName,
  img = req.body.img,
  props = req.body.props,
  type = req.body.type,
  skuSpecification = req.body.skuSpecification
  if(type != 'personproduct' && !title){
    res.send({errorMsg:'标题不能为空'})
    return
  }
  if(productName){
     SQLHelper(`
      INSERT INTO sku (skuId,img,salePrice,originalPrice,productId,productName,type,props,skuSpecification) VALUES 
      ('${skuId}','${img}','${salePrice}','${originalPrice}','${productId}','${productName}','personproduct','${props}','${skuSpecification}')
     `).then(ret => {
        res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
    })
  }else{
    res.send({errorMsg:'请传入参数错误'})
  }
})

//删除单品信息
app.delete('/admin/index/personproduct',(req,res) => {
  let indexId = req.query.indexId
  if(indexId){
      SQLHelper(`
      UPDATE sku 
      set state = 0 
      WHERE _id = ${indexId}
      `).then(ret => {
          res.send(ret)
        })
  }else{
    res.send({errorMsg:'请传入参数错误'})
  }
})


//修改单品信息
// //indexId 主码_id 必填
app.put('/admin/index/personproduct', (req, res) =>{
  if(req.body.indexId){
    //需要修改的项
    let updateTime = new Date().getTime()
    let updateKey=['skuId','salePrice','originalPrice','productId','productName','img','props','skuSpecification']
    let updataValues = [`updateTime=${updateTime}`]
    for(let i = 0;i< updateKey.length; i++){
      let key=updateKey[i],value =req.body[key]
      if(value !==undefined)updataValues.push(`${key}='${value}'`)//判断哪些项需要修改
    }
   SQLHelper(`UPDATE sku set ${updataValues.join(',')} WHERE _id =${req.body.indexId}`).then(ret =>{
     res.send(ret)
   })
 }else{
   res.send({errorMsg:'传入参数错误'})
 }
   })
}